package cn.lkk.samples.lang.reflection;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * 演示如何实现 Array.copyOf() 方法
 */
public class CopyOfTest {
    public static void main(String[] args) {
        Integer[] small = {2, 4, 1, 2, 4, 5};
        //如果调用了 badCopyOf() 会报错，因为创建的是 Object[] 数组，无法转换成 Integer[]
        Integer[] large = (Integer[]) goodCopyOf(small, 10);
        System.out.println(Arrays.toString(large));
    }

    public static Object[] badCopyOf(Object[] a, int newLength) {
        Object[] newArray = new Object[newLength];
        System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
        return newArray;
    }

    /**
     * 扩充一个数组，将数组复制到一个新的更大的数组中去
     *
     * @param a         要扩充的数组
     * @param newLength 新数组的长度
     * @return 扩充之后的数组
     */
    public static Object goodCopyOf(Object[] a, int newLength) {
        Class clazz = a.getClass();
        if (!clazz.isArray())
            return null;
        Class componentType = clazz.getComponentType();
        int length = Array.getLength(a);
        Object newArray = Array.newInstance(componentType, newLength);
        System.arraycopy(a, 0, newArray, 0, Math.min(newLength, length));
        return newArray;
    }
}
